<?php
App::import('Vendor', 'recaptchalib');
class UsersController extends AppController
{
	var $name = 'Users';
	var $helpers = array('Html', 'Form');
	var $uses = array('User', 'UserType');
    var $components = array('Email');
    
    function beforeFilter(){ 
        $this->__validateLoginStatus();
    }

    function __validateLoginStatus(){ 
       if ($this->action =='login' || $this->action =='logout' || $this->action =='add' || $this->action =='activate') return;
       if($this->Session->check('User') == false){
          $this->Session->setFlash('You must be logged in to access this page');
          $this->redirect('login');
       }
    }

	function index() {
        /*$accessArray = $this->Session->read('accessArray');
        if ($accessArray['AdminAccess']) {
        	$this->Session->setFlash('You don\'t have the privilage to access this page');
        	$this->redirect(array('controller' => HOME_CONTROLLER, 'action' => 'index'));
        }*/	
		$this->User->recursive = 0;
		$this->set('users', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid User', true));
			$this->redirect(array('action' => 'index'));
		}
		
		$user = $this->User->find('first', array(
										'conditions' => array(
											'User.id' => $id
										),
										'recursive' => -1
									)
								);
		
		if(!$user){
			$this->Session->setFlash(__('Invalid user',true));
			$this->redirect(array('controller'=>HOME_CONTROLLER,'action'=>'index'));
		}
		$this->set('user', $user);
	}

	function add() {
		if (!empty($this->data)) {
		    //make sure the passwords match
			if ($this->data['User']['password']!=$this->data['User']['confirm-password']){
				$this->Session->setFlash(__('passwords dont match', true));
				return;
			}
            $privatekey = "6LfeRAsAAAAAAHn4bicUWhVzrKVyW2T5xyPESiWW";
            $resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);

            if (!$resp->is_valid) {
                $this->Session->setFlash(__('invalid captcha', true));
				return;                              
            }
            
			$this->User->create();
			
			$newUser = array();
			
			$newUser['User']['username']=$this->data['User']['username'];
			$newUser['User']['first_name']=$this->data['User']['first_name'];
			$newUser['User']['middle_name']=$this->data['User']['middle_name'];
			$newUser['User']['last_name']=$this->data['User']['last_name'];
			$newUser['User']['birthdate']=$this->data['User']['birthdate'];
			$newUser['User']['email']=$this->data['User']['email'];			
			$newUser['User']['phone_number']=$this->data['User']['phone_number'];
			//under graduate or graduate
			if ($this->data['User']['academic_year'] == '4')
                $newUser['User']['academic_year'] = 'graduate';
            else
    			$newUser['User']['academic_year']=$this->User->calc_academic_year($this->data['User']['academic_year']);
			
            $newUser['User']['acm_member']=$this->data['User']['acm_member'];
            if (!empty($this->data['User']['custom_link_url']))
    			$newUser['User']['custom_link_url']=$this->data['User']['custom_link_url'];
			
			//password
			$newUser['User']['password']=md5($this->data['User']['password']);
			$newUser['User']['profile_picture_url'] = 'the url of the picture';
			
			//the key generation logic may better be put in another method
			$newUser['User']['activation_key'] = md5($newUser['User']['middle_name'].$newUser['User']['password'].microtime(true).mt_rand(10000,90000));
			
			if ($this->User->save($newUser)) {
				$this->Session->setFlash(__('you have been registered', true));
				$newUser['User']['id'] = $this->User->id;
				$this->__sendActivationMail($newUser);
				$this->redirect('login');
			} else {
				$this->Session->setFlash(__('The User could not be saved.', true));
			}
		}
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid User', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->User->save($this->data ,true,array('first_name','middle_name','last_name','birthdate','email','academic_year','acm_member','phone_number','custom_link_url'))) {
				$this->Session->setFlash(__('The User has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
		    if ($this->Session->read('User.id') != $id){
		        //if the user alters the id to go to edit another users id
		        //this will redirect him to index
    			$this->redirect(array('action' => 'index'));		        
		    }
			$this->data = $this->User->read(null, $id);			
		}
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for User', true));
			$this->redirect(array('action' => 'index'));
		}
		if ($this->User->del($id)) {
			$this->Session->setFlash(__('User deleted', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__('The User could not be deleted. Please, try again.', true));
		$this->redirect(array('action' => 'index'));
	}
    
    function login(){
        if(!empty($this->data)){
            if(($user = $this->User->validateLogin($this->data['User'])) == true){
                $this->Session->write('User', $user);
				$this->__setAccessArray($user);
                $name =  $this->Session->read('User.first_name');
                $last_name = $this->Session->read('User.last_name');
                $this->Session->setFlash('Welcome' . ' '.$name . ' ' .$last_name);
                $this->redirect('index');
                return;
            }
            else{
                $this->Session->setFlash(__('Sorry, the information you\'ve entered is incorrect.'));
                return;
            }
        }
    }

	function __setAccessArray($user)
	{
		$accessStr = $this->UserType->find
		( 'first',
			array
			(
				'fields' => 'UserType.privilage',
				'conditions' => array('UserType.id' => $user['user_type_id']),
				'recursive' => -1
			)
		);
		$accessStr = $accessStr['UserType']['privilage'];
		$accessArray['AdminAccess'] =  $accessStr{0};
		$accessArray['UserManager'] =  $accessStr{1};
		$accessArray['CreateSeason'] = $accessStr{2};
		$accessArray['CreateBoard'] =  $accessStr{3};
		$accessArray['CreateEvent'] =  $accessStr{4};
		$accessArray['DeleteEvent'] =  $accessStr{5};
		$accessArray['Attendance'] =   $accessStr{6};
		$accessArray['UploadBulk'] =   $accessStr{7};
		$this->Session->write('accessArray', $accessArray);
	}

    function logout(){
    	$this->Session->destroy('User');
		$this->Session->destroy('acessArray');
    	$this->Session->setFlash('You\'ve successfully logged out.');
        $this->redirect('login'); 
    }

    //sending an activation mail to the user    
    function __sendActivationMail($userData){
        $this->Email->to = $userData['User']['email'];
        $this->Email->subject = 'ACM Alex Chapter Account Activation email';
        $this->Email->replyTo = 'noreply@acmalex.com';
        $this->Email->from = 'ACM ALEX Chapter <noreply@acmalex.com>';
        //use the activation mail template
        $this->Email->template = 'activation-mail'; 
        //Send as 'html', 'text' or 'both' (default is 'text') 
        $this->Email->sendAs = 'both'; 
        //Set template parameter 
        $this->set('id', $userData['User']['id']);
        $this->set('name', $userData['User']['first_name'].' '.$userData['User']['last_name']);
        $this->set('hash', $userData['User']['activation_key']);
        
        
        //need to handle this case
        if ( $this->Email->send() ) { 
            $this->Session->setFlash('activation mail sent'); 
        } else { 
            $this->Session->setFlash('there was a problem in sending activation mail'); 
        } 
    }
    
    function activate($id,$hash){
        $user = $this->User->find('first',array('conditions'=> array('id'=>$id),'recursive'=>-1));
        if(!user){
        	$this->Session->setFlash(__('Invalid User', true));
			$this->redirect(array('action' => 'index'));	
        }
        $user = $this->User->read(null, $id);
        if ($hash == $user['User']['activation_key']){
            $user['User']['activation_key'] = '';
            $this->User->save($user,false,array('activation_key'));
           	$this->Session->setFlash('Your account was activated');
        }else{
        	$this->Session->setFlash('invalid account');
        }
        $this->redirect('login');
    }
}
?>
